import { defineStore } from "pinia";
import { compile } from "html-to-text";
import { getUserInfo } from "@/api";
import { ref } from "vue";

export const useHtmlToText = defineStore("htmlToText", () => {
  const options = {
    wordwrap: 80,
  };
  const convert = compile(options);

  return { convert };
});
export type UserInfo = {
  nickname?: string;
  roles?: string[]; // "PROJECT" | "AUDIT" | "INDICATOR" | "ADMIN"
  token?: string;
  userId?: number;
  username?: string;
};
export const useUserInfo = defineStore("userInfo", () => {
  const userInfo = ref<UserInfo>({});
  /**
   * @description: 用户数据是否已经获取，未获取则调用接口
   */
  const isReady = () => {
    return new Promise((resolve, reject) => {
      if (userInfo.value.userId) {
        resolve(userInfo.value);
      } else {
        getUserInfo()
          .then((res: any) => {
            userInfo.value = res || {};
            resolve(userInfo.value);
          })
          .catch((e) => {
            console.error(e);
            reject(e);
          });
      }
    });
  };
  return {
    userInfo,
    isReady,
    refresh: (val: UserInfo) => {
      userInfo.value = val;
    },
  };
});
